package com.powerhousecreative.q;

import java.util.ArrayList;

import org.json.JSONException;

import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.util.Log;

/**
 * 
 * @author Kenny Liao 
 * 
 */
public class GridViewAdapter extends ArrayAdapter<MainGridItem> {
	private Context context;
	private int layoutResourceId;
	private ArrayList<MainGridItem> data = new ArrayList<MainGridItem>();

	public GridViewAdapter(Context context, int layoutResourceId,
			ArrayList<MainGridItem> data) {
		super(context, layoutResourceId, data);
		this.layoutResourceId = layoutResourceId; 
		this.context = context;
		this.data = data;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		ViewHolder holder = null;

		if (v == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			v = inflater.inflate(layoutResourceId, parent, false);
			holder = new ViewHolder();
			holder.imageTitle = (TextView) v.findViewById(R.id.title);
			holder.image = (ImageView) v.findViewById(R.id.thumbnail);
			holder.image.setOnClickListener(new CellClickListener (position));
			v.setTag(holder);
		} else {
			holder = (ViewHolder) v.getTag();
		}

		MainGridItem item = data.get(position);
		holder.imageTitle.setText(item.getTitle());
		
		ImageLoader.getInstance().displayImage(item.getImageUrl(), holder.image);		
		return v;
	}

	static class ViewHolder {
		TextView imageTitle;
		ImageView image;
	}
	
	private class CellClickListener implements OnClickListener{
		private int position;
		
		public CellClickListener (int index) {
			position = index;
		}
		
		@Override
        public void onClick(View v)  {
			try {
				((MainActivity) context).showDetailView(position);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }	
	}
}